package mysql.work01;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BankService {
    public static Map<String, Account> accountMap = new HashMap<>();
    public static List<TransactionRecord> transList = new ArrayList<>();

    /**
     * 执行一条交易记录，并更新账户余额。同时，将该记录添加到交易日志列表中。
     *
     * @param record 交易记录
     */
    public void executeTransaction(TransactionRecord record) {
        //先判断交易类型，拿到交易账户里的账户余额进行操作
        TransactionType transType = record.getTransType();
        //获得要交易的账户对象
        Account transAccount = accountMap.get(record.getCounterpartyAccount());
        switch (transType) {
            case DEPOSIT://存款
            case TRANSFER_IN:// 转账收入
                transAccount.setBalance(transAccount.getBalance() + record.getTransAmount());
                //设置交易后余额
                record.setPostBalance(transAccount.getBalance() + record.getTransAmount());
            case WITHDRAWAL:
            case TRANSFER_OUT://取款, 转账支出
                transAccount.setBalance(transAccount.getBalance() - record.getTransAmount());
                //设置交易后余额
                record.setPostBalance(transAccount.getBalance() - record.getTransAmount());
        }
        //将该记录添加到交易列表中
        transList.add(record);
        //将该记录添加到日志中
        String filepath="E:\\2025-cx\\project\\PJ\\J01\\Javase\\Temp\\accountlog.txt";
        FileWriter writer=null;
        try {
            writer = new FileWriter(filepath,true);
            //交易时间，类型，金额，对方账户，交易后余额。
            writer.write(String.valueOf(transType)+','+ record.getTransAmount()+","+record.getCounterpartyAccount()+","+record.getPostBalance()+"\n");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (writer!=null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * 导出指定账户在某个时间范围内的所有交易记录到CSV文件。
     * CSV文件格式：交易时间，类型，金额，对方账户，交易后余额。
     * 同时在控制台输出：该时间范围内的总收入和总支出。
     *
     * @param accountNumber 要查看的账户号码
     * @param start         开始时间
     * @param end           结束时间
     * @param filePath      导出文件的存放位置
     */
    public void exportAuditLog(String accountNumber, LocalDateTime start, LocalDateTime end, String filePath) {
        //要查询账户的交易记录
        List<TransactionRecord> tempTransList = new ArrayList<>();
        //总收入
        double sumIn = 0;
        //总支出
        double sumOut = 0;
        for (TransactionRecord t : transList) {
            if (t.getCounterpartyAccount().equals(accountNumber) && t.getTimestamp().isAfter(start) && t.getTimestamp().isBefore(end)) {
                tempTransList.add(t);
                switch (t.getTransType()) {
                    case DEPOSIT, TRANSFER_IN ->//存款 , 转账收入
                            sumIn += t.getTransAmount();
                    case WITHDRAWAL, TRANSFER_OUT ->//取款, 转账支出
                            sumOut += t.getTransAmount();
                }
            }
        }
        System.out.println("该时间范围内的 总收入：" + sumIn + "总支出：" + sumOut);
        //创建一个字符输入流，将每一条交易记录都写到文件中
        //创建文件对象
        File file = new File(filePath);
        FileOutputStream out = null;
        OutputStreamWriter osw = null;
        try {
            out = new FileOutputStream(file);
            osw = new OutputStreamWriter(out,  "UTF-8");
            // 写入UTF-8 BOM头，帮助Excel识别编码
            osw.write("\uFEFF");
            osw.write("交易时间");
            osw.write(",");
            osw.write("类型");
            osw.write(",");
            osw.write("金额");
            osw.write(",");
            osw.write("对方账户");
            osw.write(",");
            osw.write("交易后余额");
            osw.write("\r\n");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        for ( TransactionRecord t:tempTransList) {
            //内容
            try {
                osw.write(String.valueOf(t.getTimestamp()));
                osw.write(",");
                osw.write(String.valueOf(t.getTransType()));
                osw.write(",");
                osw.write(String.valueOf(t.getTransAmount()));
                osw.write(",");
                osw.write(String.valueOf(t.getCounterpartyAccount()));
                osw.write(",");
                osw.write(String.valueOf(t.getPostBalance()));
                osw.write("\r\n");

                osw.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        try {
            out.close();
            osw.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
